package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo22PI {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
    conf.setMaster("local[8]")
    conf.setAppName("pi")
    val sc = new SparkContext(conf)


    val list: Range = 0 until 100000000

    //总数
    val length: Int = list.length


    //1、生成一个包含很多行的一个rdd
    val listRDD: RDD[Int] = sc.parallelize(list, 8)

    //2、循环随机生成点, 随机生成正方形内的点
    val pointsRDD: RDD[(Double, Double)] = listRDD.map(i => {
      //生成-1 到1 的随机数
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1
      (x, y)
    })


    //取出圆内的点
    val yuanPointRDD: RDD[(Double, Double)] = pointsRDD.filter {
      case (x: Double, y: Double) =>
        (x * x + y * y) < 1
    }

    //套公式
    val PI: Double = yuanPointRDD.count().toDouble / length * 4.0

    println(s"PI is :$PI")

  }

}
